#include	"unp.h"

void				sig_chld(int);

int
main(int argc, char **argv)
{
	int					listenfd, connfd;
	pid_t				childpid;
	socklen_t			clilen;
	struct sockaddr_in	cliaddr, servaddr;
	//void				sig_chld(int);

	listenfd = Socket(AF_INET, SOCK_STREAM, 0);

	bzero(&servaddr, sizeof(servaddr));
	servaddr.sin_family      = AF_INET;
	servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
	servaddr.sin_port        = htons(SERV_PORT);

	Bind(listenfd, (SA *) &servaddr, sizeof(servaddr));

	Listen(listenfd, LISTENQ);

	Signal(SIGCHLD, sig_chld);	/* must call waitpid() */

	for ( ; ; ) {
		clilen = sizeof(cliaddr);
		if ( (connfd = accept(listenfd, (SA *) &cliaddr, &clilen)) < 0) {
			if (errno == EINTR)
				continue;		/* back to for() */
			else
				err_sys("accept error");
		}

		if ( (childpid = Fork()) == 0) {	/* child process */
			Close(listenfd);	/* close listening socket */
			//str_echo(connfd);	/* process the request */
			///////////////////////////////////////////////////////////////////////
			ssize_t		n;
			char		buf[MAXLINE];
			char		tmp[MAXLINE];
			int 		byteCount = 0;
			int 		wordCount = 0;
			int			lineCount = 0;
			int			totalByte = 0;
			int			totalWord = 0;
			int 		i;

			again:
				while ((n = read(connfd, buf, MAXLINE)) > 0){
					if(n==2 && buf[0] =='.'){
						sprintf(tmp, "=Total Byte Counted: %d =Total Word Counted: %d =Total Line Counted: %d\n", totalByte, totalWord, lineCount);
						Writen(connfd, tmp, strlen(tmp));
						Close(connfd);
					}
					else{
						lineCount++;
						byteCount = n-1;
						wordCount = 1;
						if(n == 1 && buf[0] == '.'){
								sprintf(tmp, "END has been detected.\n");
								Writen(connfd, tmp, strlen(tmp));
								Close(connfd);
						}
						for(i=0; i<n;i++){
							if(buf[i] == ' ' || buf[i] == "\t")
								wordCount++;
						}
						sprintf(tmp, ">>>in this line >Byte counted: %d >Word counted: %d\n", byteCount, wordCount);
						Writen(connfd, tmp, strlen(tmp));
						totalByte += byteCount;
						totalWord += wordCount;
					}
				}

				if (n < 0 && errno == EINTR)
					goto again;
				else if (n < 0)
					err_sys("str_echo: read error");


			////////////////////////////////////////////////////////////////////////
			exit(0);
		}
		Close(connfd);			/* parent closes connected socket */
	}
}

void sig_chld(int signo)
	{
		pid_t	pid;
		int		stat;

		while ( (pid = waitpid(-1, &stat, WNOHANG)) > 0) {
			/* printf("child %d terminated\n", pid); */
		}
		return;
	}
